package com.zzc.another;

/**
 * Created by Administrator on 2017/4/7 0007.
 */

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.util.List;


@Controller
@RequestMapping("/fileUploadController")
public class FileUploadController extends MultiActionController {

    public ModelAndView uploadFiles(HttpServletRequest request, HttpServletResponse response) {
        System.out.println("啊啊啊啊啊啊啊啊啊啊");
        ModelAndView mav = new ModelAndView();
        // 转型为MultipartHttpRequest
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获得上传的文件（根据前台的name名称得到上传的文件）
        MultiValueMap<String, MultipartFile> multiValueMap = multipartRequest.getMultiFileMap();
        List<MultipartFile> file = multiValueMap.get("clientFile");
        //MultipartFile file = multipartRequest.getFile("clientFile");
        if(!file.isEmpty()){
            //在这里就可以对file进行处理了，可以根据自己的需求把它存到数据库或者服务器的某个文件夹
            System.out.println("================="+file.get(0).getName() + file.get(0).getSize());
        }

        return mav;
    }

    @RequestMapping(value="/uploadFile", method= RequestMethod.POST)
    public String uploadFile(@RequestParam("avatar") MultipartFile clientFile, HttpSession session)throws Exception{
        System.out.println("成功访问");
        if (!clientFile.isEmpty()) {
            //在这里就可以对file进行处理了，可以根据自己的需求把它存到数据库或者服务器的某个文件夹
            System.out.println("================="+clientFile.getSize());
            String realPath="E:\\programme\\code\\IntellijIDEA\\practice\\web\\images";
            FileUtils.copyInputStreamToFile(clientFile.getInputStream(), new File(realPath,"zzc.jpg"));//clientFile.getOriginalFilename()
            String virtualPath="E:\\programme\\code\\IntellijIDEA\\practice\\out\\artifacts\\practice_Web_exploded\\images";
            FileUtils.copyInputStreamToFile(clientFile.getInputStream(), new File(virtualPath,"zzc.jpg"));
        }
        return "success";
    }
}
